package com.dongdongshop.service.impl;

import com.dongdongshop.constant.RedisNewsConst;
import com.dongdongshop.mapper.TbOrderItemMapper;
import com.dongdongshop.mapper.TbOrderMapper;
import com.dongdongshop.pojo.Cart;
import com.dongdongshop.pojo.TbOrder;
import com.dongdongshop.pojo.TbOrderItem;
import com.dongdongshop.pojo.VoAddress;
import com.dongdongshop.service.TbOrderServiceI;
import com.dongdongshop.util.IdWorker;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

@Service
@com.alibaba.dubbo.config.annotation.Service
public class TbOrderServiceImpl implements TbOrderServiceI {

    @Autowired
    private TbOrderMapper tbOrderMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private IdWorker idWorker;

    @Autowired
    private TbOrderItemMapper tbOrderItemMapper;

    @Override
    public void insertorder(String username, VoAddress addressVo, String paymentType) {
        //获取购物车数据
        List<Cart> cartList =(List<Cart>)redisTemplate.boundHashOps(RedisNewsConst.cartList).get(username);
        //获取收货地址
        String cityName =  addressVo.getCity();
        String provinceName = addressVo.getProvince();
        String addresss = addressVo.getAddress();
        String areName = addressVo.getArea();
        String address = provinceName + cityName + addresss + areName;

        for (Cart cart : cartList) {
            //生成订单
            long pid = idWorker.nextId();
            TbOrder order = new TbOrder();
            order.setOrderId(pid);
            order.setUserId(username);//用户名
            order.setPaymentType(paymentType);//支付类型
            order.setStatus("1");//支付状态 2已付款。1未付款
            order.setCreateTime(new Date());//创建时间
            order.setUpdateTime(new Date());//修改时间
            order.setReceiverAreaName(address);//收货地址
            order.setReceiverMobile(addressVo.getMobile());//电话号
            order.setReceiver(addressVo.getContact());//收货人姓名
            order.setSourceType("2");//默认PC端
            order.setSellerId(cart.getSellerId());


            //循环购物车明细
            double money = 0;
            for (TbOrderItem tbOrderItem : cart.getOrderItemList()) {
                long orderId = idWorker.nextId();
                tbOrderItem.setId(orderId);
                tbOrderItem.setOrderId(pid);

                tbOrderItem.setSellerId(cart.getSellerId());
                money += tbOrderItem.getTotalFee().doubleValue();
                tbOrderItemMapper.insertSelective(tbOrderItem);
            }
            order.setPayment(new BigDecimal(money));
            tbOrderMapper.insertSelective(order);
        }
        //增加成功删除redis中缓存的购物车
        redisTemplate.boundHashOps(RedisNewsConst.cartList).delete(username);
    }
}
